<?php

/**
 * Created by PhpStorm.
 * User: 97438
 * Date: 2019/9/17
 * Time: 20:10
 */
namespace app\model;
use think\Model;

class UserModel extends Model
{
    protected $name = 'user';
    protected $pk = 'userId';
    public $error = '';
    public function encryptPwd($pwd)
    {
        if (empty($pwd)) {
            return '';
        }
        $pwd = md5(trim($pwd));
        $pwd=strtolower(trim($pwd));
        $p= md5($pwd.$this->pwdKey);
        return $p;
        //return md5($pwd.$this->pwdKey);
    }

    /**
     * 根据userid查询用户信息
     * @param $userId
     * @return array|null|Model
     */
    public function getUser($userId){
        $where = array('userId'=>$userId);
        $user = $this->where($where)->field('userId,mob,token')->find();
        return $user;
    }

    /**
     * 登录接口
     * @param $mob
     * @param $pwd
     * @return array
     */
    public function login($mob,$pwd){
        $where = array(
            'mob' => $mob,
            'pwd' => $this->encryptPwd($pwd),
        );
        $user = $this->where($where)->field('userId,mob')->find();
        if(!empty($user)){
            $time = time();
            $token = base64_encode(rand(1000,9999).$user->userId.$time);
            $data = array(
                'token' => $token,
                'loginTime' => date("Y-m-d H:i:s",$time),
            );
            $loginUser = $this->update($data,array('userId'=>$user->userId));
            $data['userId'] = $user->userId;
            $data['mob'] = $user->mob;
            return $data;
        }else{
            //可把登录失败次数记录到缓存或其他地方做登录限制判断
        }
    }

    /**
     * 注册
     * @param $mob
     * @param $pwd
     * @return Model|void|static
     */
    public function regist($mob,$pwd){
        $vuser = $this->where(array('mob'=>$mob))->field('userId')->find();
        if(!empty($vuser)){
            $this->error = '该手机号以被注册';
            return;
        }
        $data = array(
            'mob' => $mob,
            'pwd' => $this->encryptPwd($pwd),
            'registerDate' => date("Y-m-d H:i:s"),
        );
        $user = $this->create($data);
        return $user;
    }

    /**
     * 根据token获取用户信息
     * @param $token
     * @return array|null|Model
     */
    public function getByToken($token){
        $where = array(
            'token'=>$token,
        );
        $user = $this->where($where)->field('userId,mob,pwd,loginTime,registerDate')->find();
        return $user;
    }
}